package com.pig.easy.bpm.service.impl;

import com.pig.easy.bpm.dto.response.ConfigTemplateDTO;
import com.pig.easy.bpm.entity.ConfigDO;
import com.pig.easy.bpm.entityError.EntityError;
import com.pig.easy.bpm.mapper.ConfigMapper;
import com.pig.easy.bpm.service.ConfigService;
import com.pig.easy.bpm.service.ConfigTemplateService;
import com.pig.easy.bpm.utils.BeanUtils;
import com.pig.easy.bpm.utils.BestBpmAsset;
import com.pig.easy.bpm.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author pig
 * @since 2020-05-21
 */
@Service
@Slf4j
public class ConfigServiceImpl extends BeseServiceImpl<ConfigMapper, ConfigDO> implements ConfigService {

    @Autowired
    ConfigMapper configMapper;

    @Autowired
    ConfigTemplateService configTemplateService;

    @Cacheable(value = "config", key = "#p0.concat('-').concat(#p1)", unless = "#result == null || #result.entityError == null || #result.entityError.code != 200 || #result.data == null ")
    @Override
    public Result<Object> getConfigValue(String tenantId, String configKey) {

        BestBpmAsset.isAssetEmpty(tenantId);
        BestBpmAsset.isAssetEmpty(configKey);

        ConfigDO config = configMapper.getConfigValue(tenantId, configKey);
        if (config == null) {
            Result<ConfigTemplateDTO> result = configTemplateService.getConfigTemplate(configKey);
            if (result.getEntityError().getCode() != EntityError.SUCCESS.getCode()) {
                return Result.responseError(result.getEntityError());
            }
            config = BeanUtils.objectToBean(result.getData(), ConfigDO.class);
            if (config != null) {
                config.setConfigKey(result.getData().getTemplateKey());
                config.setConfigValue(result.getData().getTemplateValue());
                config.setConfigType(result.getData().getTemplateType());
            }
        }

        return Result.responseSuccess(getConfigValueByKey(config));
    }
}
